package rpg.writer.scripts.impl;

import rpg.engine.model.When;
import rpg.writer.scripts.ScriptWarning;

public final class WhenTool {
    private WhenTool() {
        super();
    }

    public static When parse(Integer lineNumber, String line,
            AnalyzerContext context) {
        if (!line.startsWith(ScriptAnalyzer.PREFIX_WHEN)) {
            context.addWarning(ScriptWarning.inputBad(lineNumber, line,
                    "Business logic failure, line does not begin with "
                            + ScriptAnalyzer.PREFIX_WHEN));
            return null;
        }

        final When.Builder wb = new When.Builder();
        // [When INVENTORY_HAS $20]
        final int space0 = line.indexOf(" ");
        final int space1 = line.indexOf(" ", space0 + 1);

        final String typeCode = line.substring(1 + space0, space1);
        final When.Type type;
        try {
            type = When.Type.valueOf(typeCode);
        } catch (final RuntimeException re) {
            context.addWarning(ScriptWarning.notRecognized(lineNumber, line,
                    typeCode));
            return null;
        }

        wb.type(type);
        wb.storyID(context.getStoryID());
        switch (type) {
            case ACT_IS:
            case IS_WEARING:
            case INVENTORY_HAS:
                wb.targetID(context.getStoryID() + ":"
                        + line.substring(1 + space1, line.length() - 1));
                break;
            case TOKEN_MISSING:
                wb.targetID(line.substring(1 + space1, line.length() - 1));
                break;
            default:
                context.addWarning(ScriptWarning.notImplemented(lineNumber,
                        line, "TBD"));
                return null;
        }

        return wb.build();
    }

}
